<template>
  <!-- action：头像上传时服务端的地址，用在自动上传时，人资是手动上传头像，自己写JS代码实现上传
               该属性毕传的，如果无用，设置为空字符串即可
  -->
  <!-- show-file-list：展示上传文件列表的，人资一次只能上传一个头像，不需要展示列表 -->
  <!-- on-success：头像上传成功之后的处理函数，如果是手动上传头像则不需要，成功和失败的处理自己写代码实现 -->
  <!-- before-upload：头像上传之前的校验处理，比如校验图片的格式和大小 -->
  <el-upload

    class="avatar-uploader"
    action="https://jsonplaceholder.typicode.com/posts/"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="handleUpdate"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    handleUpdate(param) {
      // 初始化Cos
      const cos = new COS({
        SecretId: 'AKIDLXVHp9F9qKaeV9ZkiSxEIAoEhxzmLtLb',
        SecretKey: '6ye5QZWKxNYWOHF2bx78xc7PVO4Yrzud'
      })

      // 调用上传方法
      cos.putObject({
        Bucket: 'kunkun-1318646252',
        Region: 'ap-beijing',
        Key: param.file.name,
        StorageClass: 'STANDARD',
        Body: param.file
      }, (err, data) => {
        if (data.statusCode === 200 && data.Location) {
          this.$emit('input', 'http://' + data.Location)
        } else {
          this.$message.error(err.Message)
        }
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG PNG GIF BMP 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt5M
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

